<?php
namespace Admin\Controller;
use Admin\Model\AuthRuleModel;
use Admin\Model\AuthGroupModel;

/**
 * 订单管理
 */
class OrderController extends AdminController{

	/**
	 * 订单管理首页
	 */
	public function index(){
		$status = I('status',null);
		$customers_name = I('customer');
		$ordernum = I('ordernum');
		$receiptnum = I('receiptnum');
		$vouchernum = I('vouchernum');
		$jdy_name = I('jdy_name');
		$stime = I('time-start');
		$etime = I('time-end');
		$ismh = I('ismh');
		if($ismh == "on"){
			if(!empty($customers_name)){
				$map['customers_name'] = array('LIKE','%'.$customers_name.'%');
			}
			if(!empty($ordernum)){
				$map['ordernum'] = array('LIKE','%'.$ordernum.'%');
			}
			if(!empty($receiptnum)){
				$map['receipt_num'] = array('LIKE','%'.$receiptnum.'%');
			}
			if(!empty($vouchernum)){
				$map['voucher_num'] = array('LIKE','%'.$vouchernum.'%');
			}
			if(!empty($jdy_name)){
				$map['jdy_name'] = array('LIKE','%'.$jdy_name.'%');
			}
		}else{
			if(!empty($customers_name)){
				$map['customers_name'] = $customers_name;
			}
			if(!empty($ordernum)){
				$map['ordernum'] = $ordernum;
			}
			if(!empty($receiptnum)){
				$map['receipt_num'] = $receiptnum;
			}
			if(!empty($vouchernum)){
				$map['voucher_num'] = $vouchernum;
			}
			if(!empty($jdy_name)){
				$map['jdy_name'] = $jdy_name;
			}
		}
		if(!empty($status) || $status == '0'){
			$map['status'] = $status;
		}else{
			$map['status'] = array('GT',0);
		}
		if(!empty($stime)){
			$map['orderdate'][] = array('EGT',strtotime($stime));
		}
		if(!empty($etime)){
			$map['orderdate'][] = array('ELT',strtotime($etime));
		}
		$list = $this->lists('Order',array($map),'id desc');
		int_to_stringForOder($list);
		$this->assign('status',$status);
		$this->assign('_list',$list);
		$this->meta_title = '订单管理';
		$this->display();
	}

	/**
	 * 订单明细
	 */
	public function orderdetail(){
		$id = I('id');
		$list = $this->lists('OrderDetail',array('order_id'=>$id),'id asc');
		int_to_string($list);
		$this->assign('_list',$list);
		$this->meta_title = '订单明细';
		$this->display();
	}

	/**
	 * 订单明细查询
	 */
	public function detailquery(){
		$status = I('status',null);
		$ordernum = I('ordernum');
		$goodstype = I('goodstype');
		$customers = I('customers');
		$jdy_name = I('jdy_name');
		$stime = I('time-start');
		$etime = I('time-end');
		$ismh = I('ismh');
		if($ismh == "on"){
			if(!empty($ordernum)){
				$map['ordernum'] = array('LIKE','%'.$ordernum.'%');
			}
			if(!empty($goodstype)){
				$map['type_name'] = array('LIKE','%'.$goodstype.'%');
			}
			if(!empty($customers)){
				$map['customers_name'] = array('LIKE','%'.$customers.'%');
			}
			if(!empty($jdy_name)){
				$map['jdy_name'] = array('LIKE','%'.$jdy_name.'%');
			}
		}else{
			if(!empty($ordernum)){
			$map['ordernum'] = $ordernum;
			}
			if(!empty($goodstype)){
				$map['type_name'] = $goodstype;
			}
			if(!empty($customers)){
				$map['customers_name'] = $customers;
			}
			if(!empty($jdy_name)){
				$map['jdy_name'] = $jdy_name;
			}
		}
		if(!empty($status) || $status == '0'){
			$map['status'] = $status;
		}else{
			$map['status'] = array('EGT',0);
		}
		if(!empty($stime)){
			$map['orderdate'][] = array('EGT',strtotime($stime));
		}
		if(!empty($etime)){
			$map['orderdate'][] = array('ELT',strtotime($etime));
		}

		$OrderView = D('OrderView');
		$total = $OrderView->where($map)->count();
		$listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
		$page = new \Think\Page($total, $listRows, $REQUEST);
		$list = $OrderView->where($map)->limit($page->firstRow.','.$page->listRows)->select();
		$page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
		$p =$page->show();
		int_to_stringForOder($list);
		$this->assign('_page', $p? $p: '');
		$this->assign('_list',$list);
		$this->meta_title = '订单明细';
		$this->display();
	}

	/**
	 * 代客下单
	 */
	public function placeorder(){
		$goodstypelist = $this->getGoodsTypeList();
		$gnum = count($goodstypelist);

		for ($i = 0; $i < $gnum; $i++) {
			$goodstype = $goodstypelist[$i];
			$Goodslist = D("Goods");
			$condition['status'] = 1;
			$condition['type_id'] = $goodstype["id"];
			$goodslist = $Goodslist->relation(true)->where($condition)->order('sort desc')->select();
			$goodstypelist[$i]["goodslist"] = $goodslist;
		}

		// $OrderView = D('OrderView');
		// $orderview = $OrderView->field('spe_id,sum(num) as totalnum')->where('OrderZB.status=1')->group('spe_id')->select();

		$this->assign('totalnum',$_SESSION['cart']['total_num']);
		$this->assign('goodslist',$goodslist);
		$this->assign('typelist',$goodstypelist);
		$this->meta_title = '代客下单';
		$this->display();
	}

	/**
	 * 退货
	 */
	public function returns(){
		$goodstypelist = $this->getGoodsTypeList();
		$gnum = count($goodstypelist);

		for ($i = 0; $i < $gnum; $i++) {
			$goodstype = $goodstypelist[$i];
			$Goodslist = D("Goods");
			$condition['status'] = 1;
			$condition['type_id'] = $goodstype["id"];
			$goodslist = $Goodslist->relation(true)->where($condition)->order('sort desc')->select();
			$goodstypelist[$i]["goodslist"] = $goodslist;
		}

		$this->assign('totalnum',$_SESSION['cart']['total_num']);
		$this->assign('goodslist',$goodslist);
		$this->assign('typelist',$goodstypelist);
		$this->meta_title = '退货';
		$this->display();
	}

	/**
	 * 确认订单
	 */
	public function confirm(){
		$list = $this->lists('Order',array('status=2'),'id desc');
		int_to_stringForOder($list);
		$this->assign('_list',$list);
		$this->meta_title = '订单确认';
		$this->display();
	}

	/**
	 * 打印订单
	 */
	public function printOrder(){
		$id = I('id');
		$Order = D("Order");
		$order = $Order->relation(true)->where('id='.$id)->select();
		if(count($order) > 0){
			$customers_id = $order[0]['customers_id'];
			$customer = $this->getCustomerByID($customers_id);
			$order[0]['customers_dz'] = $customer['address'];
			$order[0]['customers_lxr'] = $customer['contact'];
			$order[0]['customers_dh'] = $customer['phone'];
			$order[0]['total_rmb'] = num_to_rmb($order[0]['total']);
		}
		$this->assign('order',$order);
		$this->meta_title = '订单打印';
		$this->display("print");
	}

	/**
	 * 设置收据号
	 */
	public function setReceiptnum(){
		$id = array_unique((array)I('id',0));
		$id = is_array($id) ? implode(',', $id) : $id;
		$receiptnum = I('receiptnum');
		if (empty($id)){
			$this->error('请选择要操作的数据！');
		}

		$data    =  array('receipt_num' => $receiptnum);
        //如存在id字段，则加入该条件
        $fields = M('Order')->getDbFields();
        $where['id'] = array('in',$id);
        if(in_array('id',$fields) && !empty($id)){
            $where = array_merge( array('id' => array('in', $id )) ,(array)$where );
        }

        $msg   = array_merge( array( 'success'=>'操作成功！', 'error'=>'操作失败！', 'url'=>'' ,'ajax'=>IS_AJAX) , (array)$msg );
        if( M('Order')->where($where)->save($data)!==false ) {
            $this->success($msg['success'],$msg['url'],$msg['ajax']);
        }else{
            $this->error($msg['error'],$msg['url'],$msg['ajax']);
        }
	}

	/**
	 * 设置凭证号
	 */
	public function setVouchernum(){
		$id = array_unique((array)I('id',0));
		$id = is_array($id) ? implode(',', $id) : $id;
		$vouchernum = I('vouchernum');
		if (empty($id)){
			$this->error('请选择要操作的数据！');
		}

		$data    =  array('voucher_num' => $vouchernum);
        //如存在id字段，则加入该条件
        $fields = M('Order')->getDbFields();
        $where['id'] = array('in',$id);
        if(in_array('id',$fields) && !empty($id)){
            $where = array_merge( array('id' => array('in', $id )) ,(array)$where );
        }

        $msg   = array_merge( array( 'success'=>'操作成功！', 'error'=>'操作失败！', 'url'=>'' ,'ajax'=>IS_AJAX) , (array)$msg );
        if( M('Order')->where($where)->save($data)!==false ) {
            $this->success($msg['success'],$msg['url'],$msg['ajax']);
        }else{
            $this->error($msg['error'],$msg['url'],$msg['ajax']);
        }
	}

	public function changeStatus($method=null){
		$id = array_unique((array)I('id',0));
		$nid = is_array($id) ? implode(',', $id) : $id;
		if (empty($nid)){
			$this->error('请选择要操作的数据！');
		}
		$map['nid'] = array('in',$nid);
		switch (strtolower($method)) {
			case 'cancelorder'://作废
                $this->cancel('Order', $map );
                break;
            case 'confirmorder'://接单
                $this->confirmo('Order', $map );
                break;
            case 'sendorder'://发货
            	for ($i = 0; $i < count($id); $i++) {
            		$Order = M('Order');
            		$order = $Order->find($id[$i]);
            		if($order['status'] != 1){
            			$this->error('请选择已确认的订单！');
            		}
            	}
                $this->send('Order', $map );
                break;
            case 'deleteorder'://删除
                $this->delete('Order', $map );
                break;
            default:
                $this->error('参数非法');
				break;
		}
	}

	public function editorderstatus(){
		$id = I('get.id');
		empty($id) && $this->error('参数不能为空！');
		$this->meta_title = '订单状态';
		$this->assign('id',$id);
		$this->display();
	}

	public function saveorderstatus(){
		$id = I('id');
		$status = I('status');
		$Order = M('Order');
		$Order->status = $status;
		$Order->where('id='.$id)->save();
		if(!$Order){
		    $this->error(D('Goods')->getError());
        }else{
            $this->success($res['id']?'更新成功！':'新增成功！', U('index'));
        }
	}

	/**
	 * 提交订单
	 */
	public function addOrder(){
		$res = D('Order')->submitOrder();
		if(!$res){
		    $this->error(D('Order')->getError());
        }else{
        	$cart = $this->cart->empty_cart();
            $this->success('退货成功！', U('index'));
        }
		$this->display('index');
	}

	/**
	 * 跳转到购物车
	 */
	public function cart(){
		$cart = $this->cart->return_cart_info();
		$this->assign('customerlist',$this->getCustomerList());
		$this->assign('cart',$cart);
		$this->display();
	}

	/**
	 * 跳转到退货单
	 */
	public function returnscart(){
		$cart = $this->cart->return_cart_info();
		$this->assign('customerlist',$this->getCustomerList());
		$this->assign('cart',$cart);
		$this->display();
	}

	/**
	 * 清空购物车
	 */
	public function cleanCart(){
		$cart = $this->cart->empty_cart();
		$this->ajaxReturn($cart);
	}

	/**
	 * 从购物车删除单个商品
	 */
	public function delCart($id){
		$result = $this->cart->delete_goods($id);
		$this->success('删除成功',U('cart'),0);
	}

	public function editCartNum(){
		$id = I('post.id');
		$num = I('post.num');
		$result = $this->cart->edit_goods($id,$num);
		$this->ajaxReturn($result);
	}

	/**
	 * 添加到购物车
	 */
	public function addCart(){
		$id = I('post.speid');
		$price = I('post.price');
		$num = I('post.num');
		$unit = I('post.unit');
		$goodsname = I('post.goodsname');
		$goodsid = I('post.goodsid');
		$typeid = I('post.typeid');
		$totalnul;
		if((int)$num){
			$totalnul = $this->cart->add_goods($id,$price,$num,$unit,$goodsname,$goodsid,$typeid);
		}else{
			$totalnul = json_encode(array('state_code' => 1,'state_message' => '请输入商品数量！'));
		}
		$this->ajaxReturn($totalnul);
	}

	/**
	 * 获取商品分类
	 */
	public function getGoodsTypeList(){
		$typelist = M("GoodsType");
        $typelist = $typelist->where('status=1')->select();
        return $typelist;
	}

	/**
	 * 根据用户组获取用户，默认获取客户列表
	 */
	public function getUserList($group_id = '3'){
		$prefix   = C('DB_PREFIX');
        $l_table  = $prefix.(AuthGroupModel::MEMBER);
        $r_table  = $prefix.(AuthGroupModel::AUTH_GROUP_ACCESS);
        $model    = M()->table( $l_table.' m' )->join ( $r_table.' a ON m.uid=a.uid' );
        $_REQUEST = array();
        $userlist = $this->lists($model,array('a.group_id'=>$group_id,'m.status'=>array('egt',0)),'m.uid asc','m.uid,m.nickname,m.last_login_time,m.last_login_ip,m.status');
        return $userlist;
	}

	/**
	 * 获取客户列表
	 */
	public function getCustomerList(){
		$Customer = M("Customer");
		$customerlist = $Customer->where('status=1')->select();
		return $customerlist;
	}

	/**
	 * 获取客户信息
	 */
	public function getCustomerByID($cid){
		$Customer = M("Customer");
		$customer = $Customer->where('id='.$cid)->find();
		return $customer;
	}

	/**
	 * 根据分类ID获取商品
	 */
	public function getGoodsList($typeid = null){
		$goodslist = M("Goods");
		if($typeid != null){
        	$goodslist = $goodslist->where('type_id = '.$typeid.' AND status=1')->select();
        	if($goodslist == null){
				$goodslist = M("Goods");
        	}
		}
		//$this->ajaxReturn($goodslist);
        return $goodslist;
	}

	/**
	 * 根据分类ID获取商品
	 */
	public function getGoodsAndSpeBytidList($typeid = 1){
		$Goodslist = D("Goods");
		$goodslist = $Goodslist->relation(true)->where('type_id=$typeid')->select();
		$this->assign('goodslist',$goodslist);
		$this->ajaxReturn($goodslist);
	}

	/**
	 * 根据商品ID获取商品规格
	 */
	public function getGoodsSpeList($goodsid = null){
		$spelist = M("GoodsSpecification");
		if($goodsid != null){
        	$spelist = $spelist->where('goods_id = '.$goodsid.' AND status=1')->select();
        	if($spelist == null){
        		$spelist = M("GoodsSpecification");
        	}
		}
		$this->ajaxReturn($spelist);
        return $spelist;
	}

	public function getGoodsSpe($speid = null){
		$SpeObj = M("GoodsSpecification");
		if($speid != null){
			$speobj = $SpeObj->find($speid);
			if($speobj == null){
				$speobj = M("GoodsSpecification");
			}
		}
		$this->ajaxReturn($speobj);
	}
}